package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 每分钟检查是否有订单超时
     */
   //@Scheduled(cron = "0 * * * * ?")
    public void cancelOrderOverPayTime()
    {
        log.info("开始处理超时订单");
        LocalDateTime finalTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.getOrderByStatusAndFinalTime(Orders.UN_PAID, finalTime);

        if(ordersList != null && !ordersList.isEmpty()) {
            ordersList.forEach(order -> {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单超时，自动取消");
                orderMapper.update(order);
            });
        }
    }

    /**
     * 每天凌晨1点自动将前天的还在派送的订单设置成已完成
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void inProcessToCompile()
    {
        log.info("开始处理前天未完成的订单");
        LocalDateTime finalTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getOrderByStatusAndFinalTime(Orders.DELIVERY_IN_PROGRESS, finalTime);

        if(ordersList != null && !ordersList.isEmpty()) {
            ordersList.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }
    }

}
